package ru.arriah.servicedesk.web.client.action;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.mail.MailSender;
import ru.arriah.servicedesk.bean.ClientBean;
import ru.arriah.servicedesk.bean.DepartmentBean;
import ru.arriah.servicedesk.bean.EmployeeBean;
import ru.arriah.servicedesk.bean.MailTemplateBean;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.bean.error.RequestFormErrorBean;
import ru.arriah.servicedesk.ejb.ClientManagerLocalHome;
import ru.arriah.servicedesk.ejb.ClientManagerLocalObject;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalHome;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalObject;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.ejb.UtilityManagerLocalHome;
import ru.arriah.servicedesk.ejb.UtilityManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;

public class ProcessRequestFormAction extends DumbAction {
   protected RequestFormErrorBean requestFormErrorBean;
   
   protected RequestManagerLocalHome requestManagerHome;   
   protected OrganizationManagerLocalHome organizationManagerHome;
   protected ClientManagerLocalHome clientManagerHome;
   protected EmployeeManagerLocalHome employeeManagerHome;
   protected UtilityManagerLocalHome utilityManagerHome;

   public ProcessRequestFormAction() throws NamingException {
      super();

      requestManagerHome =
         Utils.getRequestManagerHomeInterface();
      
      organizationManagerHome =
        Utils.getOrganizationManagerHomeInterface();
      
      clientManagerHome = 
        Utils.getClientManagerHomeInterface();
      
      employeeManagerHome = 
        Utils.getEmployeeManagerHomeInterface();
      
      utilityManagerHome = 
        Utils.getUtilityManagerHomeInterface();
   }
   
   
   /**
    * Send mail to dispatcher
    * @param requestBean
    *  
    */
   public void sendMail(RequestBean requestBean) {
     try {
       EmployeeManagerLocalObject employeeManager = 
         employeeManagerHome.create();
       UtilityManagerLocalObject utilityManager = 
         utilityManagerHome.create();
       
       MailSender mailSender = new MailSender();
                  
       mailSender.setSmtpPort(config.getProperty("SMTP_PORT"));
       mailSender.setHostName(config.getProperty("SMTP_HOST_NAME"));
       mailSender.setFrom(config.getProperty("FROM"));
       mailSender.setCharset("UTF-8");
       
       mailSender.setAuthentication(
         config.getProperty("LOGIN"), 
         config.getProperty("PASSWORD")
       );
       
       MailTemplateBean mailTemplate = 
         utilityManager.selectMailTemplateByKey("NEW_REQUEST_TO_DISPATCHER");
       
       EmployeeBean dispatcher = 
         employeeManager.selectDispatcher();
       
       mailSender.setSubject(mailTemplate.getSubject());              
       
       mailSender.setContent(
         String.format(            
           mailTemplate.getBody(),
           dispatcher.getFirstName(),
           dispatcher.getFirstName(),
           new Date(),
           requestBean.getId(),
           config.getProperty("HOST")
         )
       );       
                      
       mailSender.addRecipient(dispatcher.getEmail());         
       
       mailSender.send();
       
       utilityManager.remove();
       employeeManager.remove();
     } catch (Exception e) {
       handleException(e, "sendMail");       
     }
   }
   
   
   /**
    * Validating request
    * @param requestBean
    * @return
    */
   private boolean isValid(RequestBean requestBean) {
     requestFormErrorBean = new RequestFormErrorBean();
     boolean result = true;
     if (requestBean.getClientText() == null || requestBean.getClientText().equals("")) {
       requestFormErrorBean.setClientText(config.getProperty("ERROR.REQUESTFORM.CLIENTTEXT"));
       result = false;
     }
     
     if (requestBean.getDepartmentId() == 0) {
       requestFormErrorBean.setDepartment(config.getProperty("ERROR.REQUESTFORM.DEPARTMENT"));
       result = false;
     }
     return result;
   }

   
   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
     try {
       RequestManagerLocalObject requestManager = 
         requestManagerHome.create();
       ClientManagerLocalObject clientManager = 
         clientManagerHome.create();                     
       
       int clientId = Utils.getUserId(request);
       ClientBean clientBean = clientManager.selectClient(clientId);
       
       RequestBean requestBean = new RequestBean();                             
       requestBean.setRoom(request.getParameter("room"));
       requestBean.setRegNumber(request.getParameter("regNumber"));
       requestBean.setClientText(request.getParameter("text"));
       requestBean.setOrganizationId(clientBean.getOrganizationId());
       requestBean.setDepartmentId(idVal(request.getParameter("department_id")));
       requestBean.setStatusId(1);
       requestBean.setPriority(3);
       requestBean.setRegistratorId(clientId);
       requestBean.setClientId(clientId);       
                            
       if(!this.isValid(requestBean)) {     
         OrganizationManagerLocalObject organizationManager = 
           organizationManagerHome.create();         
         
         Collection<DepartmentBean> departmentsList =
           organizationManager.selectDepartments(requestBean.getOrganizationId());
                  
         request.setAttribute("departmentsList", departmentsList);         
         request.setAttribute("error", requestFormErrorBean);

         addErrorMessage(request, config.getProperty("ERROR.REQUESTFORM_FIELDS_INVALID"));
       
         return actionMapping.getFailureTarget();
       }              
              
       if (requestManager.addRequest(requestBean, clientId)) {         
         this.sendMail(requestBean);         
           
         addInfMessage(
            request, 
            String.format(
               config.getProperty("INF.REQUEST_ADDED"), requestBean.getId()
            )
         );
       } else 
          addErrorMessage(
             request, 
             config.getProperty("ERROR.REQUEST_NOT_ADDED")
          );
             
       requestManager.remove();
       
       DisplayRequestsListAction displayRequestsListAction = 
          new DisplayRequestsListAction(this.requestManagerHome);
       
       displayRequestsListAction.setConfig(config);
       
       request.setAttribute("action", "listRequests");
       return displayRequestsListAction.execute(actionMapping, request, response);
    } catch (Exception e) {
       handleException(e, "execute");
       throw new InternalException("ErrorMessage.internal");
    }
   }
}